<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

use yii\helpers\Json;

/* ===================== 动态控件项值校验脚本 ===================== */

/** @var \yii\web\View $this View实例 */
/* @var array $formDynamicControl 表单动态控件选项 */
?>
<script>
    /** @var formData 表单数据 */
    /** @var __isPass 上文是否通过校验 */
    /** @var topToastr toastr插件 */
    /** @var bodyJsOptions 表单内容选项 */

    var _cGroupData;
    var _cCtlData;
    var _validatorMaps;
<?php foreach ($formDynamicControl as $index => $item): ?>
    if (
        __isPass
        && formData.hasOwnProperty("<?= $item['__groupField'] ?>")
        && (
            !bodyJsOptions["<?= $item['__groupField'] ?>"]["<?= $item['__field'] ?>"]['requiredWhere']
            || eval(bodyJsOptions["<?= $item['__groupField'] ?>"]["<?= $item['__field'] ?>"]['requiredWhere'])
        )
    ) {
        /** 必填条件为空或者必填条件结果是真 */
        _cGroupData = formData["<?= $item['__groupField'] ?>"];
        _cCtlData = _cGroupData["<?= $item['__field'] ?>"];
        _validatorMaps = <?= Json::encode($item['__jsItem']) ?>;

        Loop<?= $index + 1 ?>:for (var key in _cCtlData) {
            var _rowData = _cCtlData[key];
            for (var field in _rowData) {
                var _validatorOpts = _validatorMaps[field];
                if (!_validatorOpts) {
                    continue;
                }

                var _itemIsEmpty = ym2.isEmpty(_rowData[field]);
                //必填校验
                if (_itemIsEmpty && _validatorOpts.required) {
                    topToastr.warning('<?= $item['label'] ?>第' + (Number(key) + 1) + '行' + (_validatorOpts.label || field) + '不能为空。');
                    __isPass = false;
                    break Loop<?= $index + 1 ?>;
                }

                //规则校验
                if (!_itemIsEmpty && _validatorOpts.regexp && !ym2.strToRegexp(_validatorOpts.regexp).test(_rowData[field])) {
                    console.log(field + "匹配规则：", ym2.strToRegexp(_validatorOpts.regexp));
                    topToastr.warning('<?= $item['label'] ?>第' + (Number(key) + 1) + '行' + (_validatorOpts.label || field) + '不符合匹配规则。');
                    __isPass = false;
                    break Loop<?= $index + 1 ?>;
                }
            }
        }
    }
<?php endforeach; ?>
</script>
